<template>
  <el-dialog
    :title="id?'修改':'新增'"
    :visible.sync="dialogVisible"
    :show="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :before-close="handleClose"
    width="500px"
    @open="open"
  >
    <el-form ref="form" v-loading="infoLoading" :model="info" :rules="rules" label-width="100px">
      <el-scrollbar ref="myScrollbar" :wrap-class="{wrapClass: true}"
                    class="form-scrollbar" :style="id ? 'height: 370px' : 'height: 520px'">
        <div class="el-dialog-div">
          <el-form-item label="权限组" prop="ruleId">
            <el-select v-model="info.ruleId" filterable clearable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in ruleTemplates"
                v-if="item.state == 1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户组">
            <el-select
               v-model="info.groupId"
               filterable
               clearable
               placeholder="请选择"
               style="width: 100%">
              <el-option
                v-for="item in groups"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-alert
              v-if="id == ''"
              title="不选择用户组默认将以用户姓名创建新用户组"
              type="warning"
              :closable="false"
              show-icon
            />
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="info.userName" placeholder="请输入用户名,只允许英文数字"
                      @input="checkTrim('userName')"/>
          </el-form-item>
          <el-form-item label="用户姓名" prop="trueName">
            <el-input v-model="info.trueName" placeholder="请输入姓名"
                      @input="checkTrim('trueName')"/>
          </el-form-item>
          <template v-if="id == ''">
            <el-form-item label="输入密码" prop="password">
              <el-input v-model="info.password" placeholder="请输入密码" show-password/>
            </el-form-item>
            <el-form-item label="再次输入密码" prop="checkPassword">
              <el-input v-model="info.checkPassword" placeholder="请再次输入密码" show-password/>
            </el-form-item>
          </template>
          <el-form-item label="邮箱">
            <el-input v-model="info.email"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="info.state">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-scrollbar>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo">确 定</el-button>
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">取 消</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<style scoped>
/deep/ .el-dialog {
  min-width: 470px;
  max-width: 500px;
}

/deep/ .el-dialog__body {
  padding: 0;
}

.el-dialog-div {
  padding: 20px 20px 0 20px;
  min-width: 400px;
}

.el-alert {
  height: 30px;
}
</style>

<script>
import { postAction } from '@/api/common'
import common from '@/utils/common'

export default {
  name: 'edit',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: {
      type: [Number, String],
      default: ''
    },
    groups: {
      type: [Object, Array],
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      default: _ => {}
    },
    ruleTemplates: {
      type: [Object, Array],
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      default: _ => {}
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      console.log(value, this.info.password)
      if (value === '' && this.info.password !== '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.info.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: this.show,
      isChange: false,
      initForm: true,
      // 页面元素
      info: {
        ruleId: '',
        groupId: '',
        userName: '',
        trueName: '',
        password: '',
        checkPassword: '',
        email: '',
        state: 1
      },
      infoLoading: true,

      // 验证
      rules: {
        ruleId: [
          { required: true, message: '请选择权限组', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          { min: 2, max: 16, message: '用户名长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        trueName: [
          { required: true, message: '请输入用户姓名', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        checkPassword: [
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    show() {
      this.dialogVisible = this.show
      this.initForm = true
    },
    info: {
      handler: function() {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true
    }
  },

  methods: {
    async open() {
      this.infoLoading = true
      // 页面重置
      this.$nextTick(() => {
        this.$refs.myScrollbar.wrap.scrollTop = 0
        this.$refs.form.clearValidate()
      })
      // eslint-disable-next-line eqeqeq
      if (this.id != '') {
        const { data } = await postAction({ id: this.id }, 'UserEmployee/GetEmployeeInfo')
        // this.info = data
        this.info = data
        this.info.groupId = parseInt(this.info.groupId)

        console.log(this.info)
      } else {
        this.info = {
          ruleId: '',
          groupId: '',
          userName: '',
          trueName: '',
          password: '',
          checkPassword: '',
          email: '',
          state: 1
        }
      }
      this.infoLoading = false
    },
    checkTrim: function(obj) {
      this.info[obj] = common.checkAllTrim(this.info[obj])
    },
    subInfo() {
      this.$refs.form.validate(async(valid) => {
        // form验证
        if (valid) {
          this.infoLoading = true

          // eslint-disable-next-line eqeqeq
          const info = JSON.parse(JSON.stringify(this.info))
          let url
          if (this.id == '') {
            if (info.groupId === '') {
              info.groupId = 0
            }
            url = 'UserEmployee/SubAddInfo'
          } else {
            url = 'UserEmployee/SubEditInfo'
          }
          postAction(info, url).then(res => {
            // 调用父级页面方法
            this.closeAction()
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            this.infoLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm('您有未保存的修改，确定关闭此页吗？', '提示', {
          type: 'warning'
        })
          .then(_ => {
            this.$emit('update:show', false)
          })
          // eslint-disable-next-line @typescript-eslint/no-empty-function
          .catch(_ => {
          })
      } else {
        this.$emit('update:show', false)
      }
    },
    closeAction() {
      this.$emit('closeAction')
    }

  }
}
</script>
